<?php

namespace App\Observers;

use App\Models\User;
use App\Models\Inspection;
use Illuminate\Support\Facades\Log;

class UserObserver
{
	protected function setInviteCodeBeforeCreating(User $user)
	{
		if (! $user->invite_code) {
			$user->invite_code = random_number(10, $user, 'invite_code');
			$user->password = bcrypt(000000);
			// Generate invite code failed.
			if (! $user->invite_code) return false;
		}


	}

    public function creating(User $user)
    {


    	/*$credentials['phone'] = $user->phone;
		$credentials['password'] = 000000;
		$token = auth('api')->setTTL(config('api.auth_ttl'))->attempt($credentials);*/

		$sameUser = User::query()->where("phone",$user->phone)->where("grade","customer")->first();
		if($sameUser){

			$sameUser->update([
				'grade'=>'vip',
				'name'=>$user->name,
				"latitude" => $user->latitude,
			    "longitude" => $user->longitude,
			    "avatar" => $user->avatar,
			]);
			return false;
		}else{

			$this->setInviteCodeBeforeCreating($user);
		}


	    
    }

    public function deleted(User $user)
    {
	    $parent = $user->parent;
	    if ($parent and $parent->children->isEmpty()) {
		    $parent->update(['is_parent' => false]);
	    }

	    $user->delFromCache();
    }

	public function saving(User $user)
	{
		$user->name = strip_tags(clean($user->name, 'default'));
		$user->nickname = strip_tags(clean($user->nickname, 'default'));
		$user->signature = strip_tags(clean($user->signature, 'default'));

		if($user->province_code){
			$user->province  = config('areas')[$user->province_code];
		}

		if($user->city_code){

			$user->city  = config('areas')[$user->city_code];
		}
	}

    
}
